using System.Collections.Generic;

namespace ICSharpCode.TextEditor.Document
{
    public class TSQLFoldingStrategy : IFoldingStrategy
    {
        public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInformation)
        {
            return GenerateFoldMarkers(document);
        }

        public List<FoldMarker> GenerateFoldMarkers(IDocument document)
        {
            List<FoldMarker> list = new List<FoldMarker>();
            Stack<int> stack = new Stack<int>();
            string text = "";
            checked
            {
                for (int i = 0; i < document.TotalNumberOfLines; i++)
                {
                    LineSegment lineSegment = document.GetLineSegment(i);
                    int textLength = document.TextLength;
                    int j;
                    for (j = lineSegment.Offset; j < textLength; j++)
                    {
                        char charAt;
                        if ((charAt = document.GetCharAt(j)) != ' ' && charAt != '\t')
                        {
                            break;
                        }
                    }
                    if (j == textLength)
                    {
                        break;
                    }
                    int num = j - lineSegment.Offset;
                    int num2 = 0;
                    string text2 = "";
                    text2 = document.GetText(j, lineSegment.Length - num);
                    if (text2.ToLower().StartsWith("begin"))
                    {
                        stack.Push(i);
                    }
                    if (text2.ToLower().StartsWith("end") && stack.Count > 0)
                    {
                        num2 = stack.Pop();
                        list.Add(new FoldMarker(document, num2, document.GetLineSegment(num2).Length - "begin".Length, i, num + 57, FoldType.TypeBody));
                    }
                    text2 = document.GetText(j, lineSegment.Length - num);
                    if (text2.StartsWith("(") || text2.EndsWith("("))
                    {
                        stack.Push(i);
                        text = text2;
                    }
                    if (text2.StartsWith(")") && stack.Count > 0)
                    {
                        num2 = stack.Pop();
                        list.Add(new FoldMarker(document, num2, document.GetLineSegment(num2).Length - "(".Length, i, num + 57, FoldType.TypeBody));
                        text = string.Empty;
                    }
                }
                return list;
            }
        }
    }
}
